'use strict'

const http = require('http');

const server = http.createServer();

//HTTP中的请求类型 GET POST PUT DELETE OPTIONS PATCH HEAD TRACE
//请求时必须携带数据 POST PUT PATCH DELETE(可以携带也可以不携带)
let routeMap = {
    GET:{
        '/':(ctx) => {
            ctx.response.setHeader('content-type','text/html;charset="utf-8"');
            ctx.response.end("这是首页");
        },
        '/login':(ctx) => {
            ctx.response.end("This is login!");
        },
        '/update':(ctx) => {
            ctx.response.end("This is update!");
        }
    },
    POST:{
        '/login':(ctx) => {
            ctx.response.end(JSON.stringify(ctx.body));
        },
        '/upload':(ctx) => {
            console.log(ctx.headers);
            console.log(ctx.method);
            console.log(ctx.rawBody.toString('utf8'));
            ctx.response.end("OK");
        }
    },
    PUT:{
        '/update':(ctx) => {
            ctx.response.end(JSON.stringify(ctx.body));
        }
    }
}

//处理用户提交的数据的类型
//application/json --> {a:1.b:2}
//application/x-www-form-urlencoded --> a=1&b=2
function parseBody(ctx) {
    switch (ctx.headers['content-type']) {
        case 'application/json':
            try{
                ctx.body = JSON.parse(ctx.rawBody.toString('utf8'));
            }catch{
                ctx.response.statusCode = 400;
                ctx.response.end();
            }
        // a=1&b=2 --> {a:1,b:2}
        case 'application/x-www-form-urlencoded':
            let obj = {};
            let textBody = ctx.rawBody.toString('utf8');
            let arr = textBody.split('&').filter(item => item.length > 0);
            let temp;
            for(let a of arr) {
                temp = a.split('=');
                obj[temp[0]] = temp[1] || '';
            }
            ctx.body = obj;
        default:
            break;
    }
}

server.on("request",(req,res) => {
    let urlarr = req.url.split('?');
    let pathname = urlarr[0];
    
    if(routeMap[req.method] === undefined || routeMap[req.method][pathname] === undefined) {
        res.statusCode = 404;
        res.setHeader('content-type','text/html;charset="utf-8"');
        res.end("页面不存在！");
        return ;
    }

    //context
    let ctx = {
        method: req.method,
        body: null,
        request: req,
        response: res,
        headers: req.headers,
        rawBody: null
    };

    if(['P','D'].indexOf(req.method[0]) >= 0) {
        //Nodejs定义了一个Buffer类，用来创建专门存储二进制数据的缓冲区
        //Buffer在操作的时候相当于一个数组
        let bodydata = [];
        let bodylength = 0;
        req.on("data",chunk => {
            bodydata.push(chunk);
            bodylength += chunk.length;
        })
        req.on("end",() => {
            ctx.rawBody = Buffer.concat(bodydata,bodylength);
            parseBody(ctx);
            if(ctx.response.writable) {
                routeMap[req.method][pathname](ctx);
            }
        })
    } else {
        routeMap[req.method][pathname](ctx);
    }
});

server.listen(8080,() => {
    console.log("Now listening 8080!");
});